package cn.iotab.iotkit.transport.mqtt;

import cn.iotab.iotkit.transport.mqtt.conf.MqttServerConfig;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;
import io.netty.handler.ssl.SslHandler;

/**
 * @author Andrew Shvayka
 */
public class MqttTransportServerInitializer extends ChannelInitializer<SocketChannel> {

    private final MqttServerConfig config;

    private final MqttTransportContext context;

    public MqttTransportServerInitializer(MqttServerConfig config, MqttTransportContext context) {
        this.config = config;
        this.context = context;
    }

    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        SslHandler sslHandler = null;
        if (config.getSslConf().isSslEnable()) {
            sslHandler = context.getSslHandlerProvider().getSslHandler();
            pipeline.addLast(sslHandler);
        }
        pipeline.addLast("decoder", new MqttDecoder(config.getMqttConf().getMaxPayloadSize()));
        pipeline.addLast("encoder", MqttEncoder.INSTANCE);

        MqttTransportHandler handler = new MqttTransportHandler(context, sslHandler);

        pipeline.addLast(handler);
        ch.closeFuture().addListener(handler);
    }

}
